<template>
  <div class="flex justify-center items-center box-border">
    <div
      :style="{ width: props.width, height: props.height }"
      ref="barChartDom"
      v-loading="loading"
    ></div>
  </div>
</template>

<script setup>
import {
  ref,
  computed,
  watch,
  onMounted,
  markRaw,
  nextTick,
  onBeforeUnmount,
} from "vue";
import * as echarts from "echarts";
const barChartDom = ref(null);
let chartInstance = ref();
let loading = ref(true);
let props = defineProps({
  width: {
    type: String,
    default: "",
  },
  height: {
    type: String,
    default: "",
  },
  models: {
    type: Object,
    default: () => ({}),
  },
  responseData: {
    type: Object,
    default: () => ({}),
  },
});

watch(
  [() => props.models],
  () => {
    chartInit();
  },
  { deep: true }
);
watch(
  () => props.responseData,
  () => {
    if (props.responseData) {
      chartInit();
    }
  },
  {
    deep: true,
  }
);
watch([() => props.width, () => props.height], () => {
  if (chartInstance.value) {
    resize();
  }
});
const states = computed({
  get: () => props.models,
});
onMounted(() => {
  setTimeout(() => {
    chartInit();
    loading.value = false;
  }, 500);
});
const resize = () => {
  nextTick(() => {
    // console.log('states', states.value)
    chartInstance.value.resize();
  });
};
onBeforeUnmount(() => {
  chartInstance.value.dispose();
  chartInstance.value = null;
  window.removeEventListener("resize", () => {});
});
function chartInit() {
  if (!chartInstance.value) {
    chartInstance.value = markRaw(echarts.init(barChartDom.value, "dark"));
  }

  let option = {
    ...JSON.parse(JSON.stringify(states.value)),
  };
  if (Object.keys(props.responseData).length) {
    let arr = JSON.parse(JSON.stringify(props.responseData));
    option.series[0].data = [...arr];
    let allValue = 0;
    const pieUnit = "KB";
    arr.map((it) => {
      allValue += it.value;
    });
    option.series[0].label.formatter = function (params) {
      if (params.name) {
        return (
          `{name| ${
            params.name + "\u0020" + parseInt((params.value / allValue) * 100)
          } %} \n` + `{itVal|${params.value + pieUnit}}`
        );
      }
    };
  }
  option && chartInstance.value.setOption(option, true);
}

defineExpose({
  resize,
});
</script>

<style scoped lang="scss">
.charts {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}
</style>
